package cn.tedu.cs.baking.controller;

import cn.tedu.cs.baking.common.ex.BusinessException;
import cn.tedu.cs.baking.dao.AlbumMapper;
import cn.tedu.cs.baking.dao.PictureMapper;
import cn.tedu.cs.baking.pojo.dto.AlbumAddDTO;
import cn.tedu.cs.baking.pojo.po.Album;
import cn.tedu.cs.baking.pojo.po.User;
import cn.tedu.cs.baking.pojo.vo.AlbumVO;
import cn.tedu.cs.baking.pojo.vo.UserVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/albums")
@Api(tags = "相册管理")
public class AlbumController {
    @Autowired
    private AlbumMapper albumMapper;
    @Autowired
    private PictureMapper pictureMapper;

    /**
     * 新增相册
     */
    @PostMapping("/addNew")
    @ApiOperation("新增相册")
    public void addNew(@Valid @RequestBody AlbumAddDTO albumAddDTO) throws Exception {
        Object checkNameQueryResult = albumMapper.getByName(albumAddDTO.getName());
        if (checkNameQueryResult != null){
            throw new BusinessException("新增相册失败，相册名称(" + albumAddDTO.getName() + ")已存在！" );
        }
        Album album = new Album();
        BeanUtils.copyProperties(albumAddDTO, album);
        album.setSort(album.getSort() == null? 0:album.getSort());
        album.setCreateTime(new Date());
        int rows = albumMapper.insert(album);
        if (rows != 1){
            System.out.println("插入相册失败!!");
        }
    }

    /**
     * 相册列表
     */
    @GetMapping("/list")
    @ApiOperation("相册列表")
    public List<AlbumVO> getAlbumList(
            @RequestParam(required = true,defaultValue = "1") Integer pageCurrent,
            @RequestParam(required = true,defaultValue = "10") Integer pageSize){
        int index = pageSize*(pageCurrent-1);
        List<AlbumVO> list = albumMapper.getList(index,pageSize);
        return list;
    }

    @GetMapping("getByAlbumId")
    @ApiOperation("相册详情")
    public Album getByAlbumId(Long id){
        return albumMapper.selectByPrimaryKey(id);
    }

    /**
     * 根据albumId删除相册
     * @param albumId
     * @throws BusinessException
     */
    @GetMapping("/delete")
    @ApiOperation("删除相册")
    public void deleteById(Long albumId) throws BusinessException {
        int count = pictureMapper.countByAlbumId(albumId);
        if (count>0){
            throw new BusinessException("删除相册失败,因为相册下有关联的图片!!");
        }
        int rows = albumMapper.deleteById(albumId);
        if (rows != 1){
            throw new BusinessException("删除相册失败!");
        }
    }

    @PostMapping("update")
    @ApiOperation("相册更新")
    public void updateById(@Valid @RequestBody Album album){
        album.setUpdateTime(new Date());
        albumMapper.updateByPrimaryKeySelective(album);
    }
}
